package LeetCode._01_树;

public class _230_二叉搜索树中第K小的元素 {
    public class TreeNode {
       int val;
       TreeNode left;
       TreeNode right;
       TreeNode() {}
       TreeNode(int val) { this.val = val; }
       TreeNode(int val, TreeNode left, TreeNode right) {
           this.val = val;
           this.left = left;
           this.right = right;
       }
    }

    int res = 0; //存放结果
    int rank = 0; //计算排名
    public int kthSmallest(TreeNode root, int k) {
       traver(root,k);
       return res;
    }

    private void traver(TreeNode root,int k){
       if(root == null) return;
       traver(root.left,k);
       rank++; //记录当前节点是排名第几的元素

       //中序遍历的位置
       if(k==rank){ //找到了排名第K的元素
          res = root.val;
          return;
       }


       traver(root.right,k);
    }
}
